<template>
  <div class="good-detail">
    <s-header :name="'商品详情'"></s-header>
    <div class="detail-content">
      <div class="detail-swipe-wrap">
        <van-swipe class="my-swipe" indicator-color="#1baeae">
          <van-swipe-item v-for="(item, index) in banner" :key="index">
            <img :src="item.lpath" alt="">
          </van-swipe-item>
        </van-swipe>
      </div>
      <div class="good-info">
        <div class="good-price">
          {{ product.price || '' }}
        </div>
        <div class="good-title">
          {{ product.title || '' }}
          <span v-if="brand.name">
            ({{ brand.name }})
          </span>
        </div>
        <div class="good-name">
          {{ product.title || '' }}
        </div>
        <div class="good-tags" v-if="showTags">
          <van-tag class="good-tag" v-for="tag in showTags" :key="tag" plain type="danger">{{ tag }}</van-tag>
        </div>
      </div>
      <div class="good-intro">
        <ul>
          <li v-for="item in showExtraData" :key="item.key">
            <div class="good-intro-item">
              <div class="good-intro-item__label">{{ item.label }}</div>
              <div class="good-intro-item__value">{{ item.value }}</div>
            </div>
          </li>
        </ul>
      </div>
      <!-- 配送地址 -->
      <div class="delivery-address" @click="toSelectAddress">
        <div class="label">配送至：</div>
        <div :class="['address', isDistribution?'':'address-disabled']">{{ showAddress }}</div>
        <van-icon class="icon" name="arrow" color="#000" />
      </div>
      <!-- 配送描述 -->
      <div v-if="false" class="delivery-range">
        <div class="label">查看配送范围</div>
        <van-icon class="icon" name="arrow" color="#000" />
      </div>
      <!-- 配送描述 -->
      <div class="delivery-desc" v-if="distrubtion">
        <div class="label">配送描述：</div>
        <div class="wrap-content">{{ distrubtion }}</div>
      </div>
      <!-- 品牌 -->
      <Brand v-if="brand.id" :brand="brand" @click="goToBrand"></Brand>
      <div class="good-content-wrapper">
        <div v-if="contentImages.length > 0" class="good-content">
          <img v-for="item in contentImages" :src="item.lpath" :key="item.id" />
        </div>
        <div v-if="contentImages.length === 0" class="good-content" v-html="product.description"></div>
      </div>
    </div>
    <div class="place-holder"></div>
    <van-action-bar>
      <!--      <van-action-bar-icon icon="chat-o" text="客服" />-->
      <!--      <van-action-bar-icon icon="cart-o" :badge="!cart.count ? '' : cart.count" @click="goTo()" text="购物车" />-->
      <!--      <van-action-bar-button type="warning" @click="handleAddCart" text="加入购物车" />-->
      <div style="width: 90%;margin: auto"><van-action-bar-button class="buy-btn" type="danger" @click="openDialog" text="立即购买" /></div>
    </van-action-bar>
  </div>
  <nut-sku v-model:visible="visible" :sku="sku" :goods="goods" @changeStepper="changeStepper" @selectSku="selectSku" @clickBtnOperate="clickBtnOperate"
    @close="close">
    <!-- 商品展示区，编号区域 -->
    <template #sku-header-extra>
      <span v-if="gift" class="nut-sku-header-right-extra">赠：{{ gift }}</span>
    </template>
    <!-- 底部按钮操作区 -->
    <template #sku-operate>
      <div>
        <!-- 附件购买 -->
        <div v-if="charges.length>0" style="box-shadow:none;padding:13px 0;width: 100vw;">
          <div style="margin-left: 20px;font-weight: bold;">附件购买</div>
          <div class="charge-list">
            <div class="charge-item" v-for="item in charges" :key="item.id">
              <div :class="['charge-icon', getChargeClass(item.name)]"></div>
              <div class="charge-info">
                <div class="name">{{ item.name }}</div>
                <div class="price">{{ item.price }}/份</div>
              </div>
              <div class="charge-count">
                <nut-input-number v-model="item.count" :step="1" :min="0" />
              </div>
            </div>
          </div>
          <div style="padding: 10px 20px;font-weight: bold;">注：餐具附件具体样式以实际收到为准</div>
        </div>
        <div class="sku-operate-box">
          <!-- <nut-button class="sku-operate-item" shape="square" type="warning">加入购物车</nut-button> -->
          <van-action-bar-button class="sku-operate-item" type="danger" @click="submit">{{btnShow}}</van-action-bar-button>
        </div>
      </div>
    </template>
  </nut-sku>
</template>

<script lang="ts" setup>
import { onMounted, computed, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { fetchGoodDetail } from '@/service/good'
import sHeader from '@/components/SimpleHeader.vue'
import { useAddress } from '@/stores/address'
import {showToast} from "vant";
import {useOrderStoreHook} from "@/stores/order";
import {fetchDistributionRule} from "@/service/distribution";
import {useLocation} from "@/stores/location";
import Brand from "@/components/Brand.vue";
import {useBrandStoreHook} from "@/stores/brand";

const route = useRoute()
const query = route.query
const router = useRouter()

const getChargeClass = (name: string) => {
  const offsetMap = {
    '贺卡': 'icon-offset-1',
    '餐具': 'icon-offset-2',
    '帽': 'icon-offset-3',
    '袋子': 'icon-offset-4',
    '蜡烛': 'icon-offset-5',
    '组合': 'icon-offset-6',
  }
  let type = '组合'
  if(name.includes('卡')) type= '贺卡'
  if(name.includes('蜡')) type= '蜡烛'
  if(name.includes('餐具')) type= '餐具'
  if(name.includes('帽')) type= '帽'
  if(name.includes('袋')) type= '袋子'
  if(name.includes('套件')) type= '组合'

  return offsetMap[type] || 'icon-offset-6'
}

//#region 标签
const showTags = computed(() => {
  const tags:string[] = []
  if(product.value?.labelName) {
    const arr: string[] = product.value.labelName.split(',')
    tags.push(...arr)
  }
  return tags
})
//#endregion

const visible = ref(false)
const selectSkuId = ref('')
const gift = ref('')
const sku = computed(() => {
  const data: any = [{
    id: 1,
    list: [],
    name: '规格'
  }]
  specs.value?.forEach(item => {
    data[0].list.push({
      active: selectSkuId.value === item.id,
      disable: false,
      id: item.id,
      name: item.name,
      spec: item,
    })
  })

  return data
})
const showPrice = ref(0)
const goods = computed(() => {
  const data = {
    skuId: product.value.id,
    price: showPrice.value,
    imagePath: product.value.imagePath
  }
  return data
})
// 切换规格类目
const selectSku = (ss) => {
  const { sku } = ss
  if (sku.disable) return false
  selectSkuId.value = sku.id
  gift.value = sku.spec.gift
  showPrice.value = sku.spec.price
}
// 底部操作按钮触发
const clickBtnOperate = (op) => {
  console.log('点击了操作按钮', op)
}
// 关闭商品规格弹框
const close = () => {
  visible.value = false
}

//#region 地址
const { address, getSelectedAddress, getAddressList } = useAddress()
const showAddress = computed(() => {
  const data = getSelectedAddress()
  return data ? (data.province + data.city + data.area + data.addr) : '请选择收货地址'
})
const getDeultAddress = async () => {
  await getAddressList()
  address.selectedId = address.selectedId || address.defaultId
}
const toSelectAddress = () => {
  router.push({
    path: '/address',
  })
}
//#endregion

//#region 配送
const isDistribution = ref(false)
// const canTake = ref(false)
const canShip = ref(false)
// const canSame = ref(false)
//
// const shipTip = ref('')
const { location } = useLocation()
const getDistribution = async () => {
  console.log(location.cityCode)
  const data: any = getSelectedAddress()
  if(!data?.cityId) return
  const res = await fetchDistributionRule(data?.cityId, selectSkuId.value, `${buyCount.value}`, data?.id)
  console.log(res)
  isDistribution.value = res.data.isDistribution != '0'
  canShip.value = res.data.canShip
  if(canShip.value) {
    // 分析配送时间
    // const validateDeliveryDates = res.data.validateDeliveryDates
  }
}
//#endregion

onMounted(async () => {
  await getGoodDetail()
  await getDeultAddress()
  await getDistribution()
})

//#region 商品详情
// 商品信息
const product = ref<any>({
  "id": "",
  "catId": "",
  "catId2": null,
  "catId3": null,
  "isYushou": false,
  "isGreeting": false,
  "imagePath": "",
  "imageWidth": "320",
  "imageHeight": "320",
  "title": "",
  "description": "",
  "commentCount": "0",
  "likeCount": "",
  "buyCount": "",
  "status": "",
  "marketPrice": "",
  "price": "",
  "canTake": "1",
  "canShip": "1",
  "distributionRuleId": "741",
  "canBuy": "1",
  "labelName": null,
  "brandId": "450",
  "images": "",
  "contentImages": "[]",
  "charges": "[]",
  "cityId": null,
  "extra_data": null
})
// 显示信息
const extraData = ref<any[]>([])
const showExtraData = computed(() => {
  const showData: any[] = []
  extraData.value.forEach((item) => {
    if (showData.length === 3) return
    showData.push(item)
  })
  return showData
})
const banner = ref<any[]>([])
const specs = ref<any[]>([])
const brand = ref<any>({})
const charges = ref<any[]>([])
const contentImages = ref<any[]>([])
const distrubtion = ref('')
const getGoodDetail = async () => {
  const id = query.id
  const res: any = await fetchGoodDetail(id)
  const good = res.data
  product.value = good.product
  const extraDataObj = good.extraData
  extraData.value = []
  const map = {
    storage: '储存方式',
    sweetness: '甜度',
    package: '包装',
    sweetness_text: '甜度说明',
    // taste: '口感',
    // material: '原材料',
  }
  for (const item in extraDataObj) {
    if (map[item]) extraData.value.push({
      key: item,
      value: extraDataObj[item],
      label: map[item]
    })
    if (item === 'distrubtion') distrubtion.value = extraDataObj[item]
  }
  brand.value = good.brand
  banner.value = good.images
  specs.value = good.specs
  brand.value = good.brand || {}
  charges.value = JSON.parse(good.product?.charges||'[]') || []
  charges.value.forEach((item) => {
    item.count = 0
  })
  contentImages.value = good.contentImages
  // 默认选择第一个规格
  if (specs.value.length > 0) {
    selectSkuId.value = specs.value[0].id
    showPrice.value = specs.value[0].price
    gift.value = specs.value[0].gift
  }
}
//#endregion

//#region 数量
const buyCount = ref(1)
const changeStepper = (count: number) => {
  buyCount.value = count
}
//#endregion
//#region 购买
const btnShow = computed(() => {
  const productFee = showPrice.value * buyCount.value
  const chargeFee = charges.value.reduce((total, cur) => {
    return  total + cur.price * cur.count
  }, 0)
  return '立即购买' + `(￥${(productFee+chargeFee).toFixed(2)})`
})
//#endregion

const orderStore = useOrderStoreHook()
const submit = () => {
  if(!selectSkuId.value) {
    showToast('未选择商品规格')
    return
  }
  const specList = specs.value.filter((item) => {
    item.isGreeting = product.value.isGreeting
    item.productName = product.value.title
    item.imagePath = product.value.imagePath
    item.count = buyCount.value
    return item.id === selectSkuId.value
  })
  const chargeList = charges.value.filter((item) => item.count>0)
  orderStore.setOrder(specList, chargeList, product.value.id)

  router.push({ path: '/create-order' })
}

const brandStore = useBrandStoreHook()
const goToBrand = () => {
  brandStore.setBrand(brand.value)
  router.push({
    path: 'brand',
  })
}

// 打开弹窗
const openDialog = () => {
  // if(!isDistribution.value) {
  //   showToast('当前地址不支持配送')
  //   return
  // }
  visible.value = true
}

</script>

<style lang="less">
@import '../common/style/mixin';

.good-detail {
  .detail-header {
    position: fixed;
    top: 0;
    left: 0;
    z-index: 10000;
    .fj();
    .wh(100%, 44px);
    line-height: 44px;
    padding: 0 10px;
    .boxSizing();
    color: #252525;
    background: #fff;
    border-bottom: 1px solid #dcdcdc;

    .good-name {
      font-size: 14px;
    }
  }

  .detail-content {
    height: calc(100vh - 50px);
    overflow: hidden;
    overflow-y: auto;

    .detail-swipe-wrap {
      .my-swipe .van-swipe-item {
        img {
          width: 100%;
          min-height: 300px;
        }
      }
    }

    .good-info {
      padding: 0 10px;

      .good-title {
        font-size: 20px;
        font-weight: bold;
        text-align: left;
        color: #333;
      }

      .good-name {
        margin: 5px 0;
        font-size: 14px;
      }

      .good-tags {
        padding: 5px 0;

        .good-tag {
          margin-right: 10px;
        }
      }

      .good-price {
        font-size: 30px;
        color: #ff0000;
        font-weight: bold;

        &::before {
          content: "￥";
          font-size: 24px;
        }
      }
    }

    .good-intro {
      width: 100%;
      background: linear-gradient(to bottom,
          #ff5e6630 0%,
          /* 顶部为红色 */
          #fff 50%,
          /* 中间部分过渡到完全透明 */
          #ff5e6630 100%
          /* 底部再次为红色 */
        );

      .good-intro-item {
        font-size: 12px;

        &__label {
          color: #868686;
          margin-bottom: 5px;
        }

        &__value {
          margin: auto;
          width: 120px;
        }
      }

      ul {
        display: flex;
        flex-wrap: wrap;
        width: 100%;
        margin: 10px 0;

        li {
          width: 120px;
          flex: 1;
          padding: 5px 0;
          text-align: center;
          font-size: 15px;
          border-right: 1px solid #dddddd66;
          box-sizing: border-box;

          &:last-child {
            border-right: none;
          }
        }
      }
    }

    .icon {
      margin-right: 10px;
      margin-left: auto;
    }

    .label {
      width: 80px;
      color: #aaa;
      flex-shrink: 0;
    }

    .delivery-address {
      display: flex;
      align-items: center;
      height: 40px;
      border-bottom: 1px solid #eee;
      padding-left: 12px;
      .address-disabled {
        &::after {
          content: "(该地址无法配送)";
          color: #999;
        }
      }
    }

    .delivery-range {
      display: flex;
      align-items: center;
      height: 40px;
      border-bottom: 1px solid #eee;
      padding-left: 12px;
    }

    .delivery-desc {
      display: flex;
      align-items: center;
      min-height: 40px;
      border-bottom: 1px solid #eee;
      padding: 12px;

      .wrap-content {}
    }

    .good-content-wrapper {
      padding: 20px;

      .good-content {
        font-size: 12px;

        img {
          width: 100%;
        }
      }
    }
  }

  .van-action-bar-button--warning {
    background: linear-gradient(to right, #6bd8d8, @primary)
  }

  .van-action-bar-button--danger {
    background: linear-gradient(to right, #0dc3c3, #098888)
  }

  .place-holder {
    height: 80px;
    width: 100%;
  }
  .buy-btn {
    background: @primary;
  }
}

.sku-operate-box {
  width: 100%;
  display: flex;
  padding: 8px 10px;
  box-sizing: border-box;

  .sku-operate-item {
    flex: 1;
    background: @primary;
  }
}

.charge-list {
  max-height: 270px;
  width: 100vw;
  overflow-y: auto;
  .charge-item {
    padding: 20px;
    display: flex;
    .charge-icon {
      background-position-y: 0;
      width: 40px;
      height: 40px;
      background-image: url(https://image-oss.dangaoss.cn/common/common_20240612155044_651.png);
      background-size: 100% 700%;
    }
    .icon-offset-1 {
      background-position-y: 0;
    }
    .icon-offset-2 {
      background-position-y: -40px;
    }
    .icon-offset-3 {
      background-position-y: -80px;
    }
    .icon-offset-4 {
      background-position-y: -120px;
    }
    .icon-offset-5 {
      background-position-y: -160px;
    }
    .icon-offset-6 {
      background-position-y: -200px;
    }
    .charge-info {
      margin-left: 10px;
      display: flex;
      flex-direction: column;
      .price {
        color: @primary;
        &::before {
          content: "￥";
          font-size: 12px;
        }
      }
    }
    .charge-count {
      margin-left: auto;
    }
  }
}
</style>
